package com.bdk.middle.orchestration.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdk.middle.common.domain.PageDO;
import com.bdk.middle.common.result.ResultDO;
import com.bdk.middle.common.status.ErrorCode;
import com.bdk.middle.common.util.BeanUtilsExtends;
import com.bdk.middle.common.util.Constant;
import com.bdk.middle.orchestration.api.client.ModuleClientApi;
import com.bdk.middle.orchestration.api.domain.FunctionModuleDO;
import com.bdk.middle.orchestration.api.domain.ServiceManagerDO;
import com.bdk.middle.orchestration.api.query.FunctionModuleQueryDO;
import com.bdk.middle.orchestration.core.entity.FunctionModuleEntity;
import com.bdk.middle.orchestration.core.entity.ModuleServiceEntity;
import com.bdk.middle.orchestration.core.mapper.FunctionModuleMapper;

import com.bdk.middle.orchestration.core.mapper.ModuleServiceMapper;
import com.bdk.middle.orchestration.service.FunctionModuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.bdk.middle.orchestration.service.ServiceManagerService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Reagan
 * @since 2021-03-12
 */
@RestController
@Service
public class FunctionModuleServiceImpl extends ServiceImpl<FunctionModuleMapper, FunctionModuleEntity> implements FunctionModuleService, ModuleClientApi {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private FunctionModuleMapper functionModuleMapper;

    @Autowired
    private ModuleServiceMapper moduleServiceMapper;

    @Autowired
    private ServiceManagerService serviceManagerService;

    @Override
    public ResultDO add(FunctionModuleDO domain) {

        ResultDO result = new ResultDO();

        if(domain.getServiceIds() == null) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.FUNCTION_MODULE_NOT_SERVICE_ERROR);
            logger.debug("error code：" + ErrorCode.FUNCTION_MODULE_NOT_SERVICE_ERROR.getCode() + " msg" + ErrorCode.FUNCTION_MODULE_NOT_SERVICE_ERROR.getMsg());
            return result;
        }

        FunctionModuleEntity entity = new FunctionModuleEntity();
        entity.setCreateDate(Calendar.getInstance().getTime());
        entity.setModifiDate(entity.getCreateDate());
        entity.setStatus(1);
        entity.setIsDelete(1);
        BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        int res = -1;
        try {
            res = functionModuleMapper.insert(entity);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.FUNCTION_MODULE_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.FUNCTION_MODULE_ADD_ERROR.getCode() + " msg" + ErrorCode.FUNCTION_MODULE_ADD_ERROR.getMsg());
            return result;
        }

        result = addModuleService(entity.getId(), domain.getServiceIds());
        return result;
    }

    private ResultDO addModuleService(String moduleId, List<String> serviceIds) {

        ResultDO result = new ResultDO();
        int res = -1;

        for(String serviceId : serviceIds) {
            ModuleServiceEntity moduleServiceEntity = new ModuleServiceEntity();
            moduleServiceEntity.setModuleId(moduleId);
            moduleServiceEntity.setServiceId(serviceId);

            try {
                res = moduleServiceMapper.insert(moduleServiceEntity);
            } catch(Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                return result;
            }
            if(res < 0) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.FUNCTION_MODULE_SERVICE_MAPPING_ERROR);
                logger.debug("error code：" + ErrorCode.FUNCTION_MODULE_SERVICE_MAPPING_ERROR.getCode() + " msg" + ErrorCode.FUNCTION_MODULE_SERVICE_MAPPING_ERROR.getMsg());
                return result;
            }

        }
        return result;
    }

    private ResultDO deleteModuleServcie(String moduleId) {

        ResultDO result = new ResultDO();
        int res = -1;
        try {
            res = moduleServiceMapper.delete(Wrappers.<ModuleServiceEntity>lambdaQuery().eq(ModuleServiceEntity::getModuleId, moduleId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.FUNCTION_MODULE_SERVICE_DELETE_ERROR);
            logger.debug("error code：" + ErrorCode.FUNCTION_MODULE_SERVICE_DELETE_ERROR.getCode() + " msg" + ErrorCode.FUNCTION_MODULE_SERVICE_DELETE_ERROR.getMsg());
            return result;
        }

        return result;
    }

    private ResultDO getModuleService(String moduleId) {

        ResultDO result = new ResultDO();

        List<ModuleServiceEntity> list  = null;

        try {
            list = moduleServiceMapper.selectList(Wrappers.<ModuleServiceEntity>lambdaQuery().eq(ModuleServiceEntity::getModuleId, moduleId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<ServiceManagerDO> doList = new ArrayList<>();

        for(ModuleServiceEntity entity : list) {
            result = serviceManagerService.get(entity.getServiceId());
            if(!result.isSuccess()) {
                return result;
            }
            doList.add((ServiceManagerDO) result.getModel(ResultDO.FIRST_MODEL_KEY));
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
        return result;
    }


    @Override
    public ResultDO edit(FunctionModuleDO domain) {

        FunctionModuleEntity entity = new FunctionModuleEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        entity.setModifiDate(Calendar.getInstance().getTime());
        int res = -1;
        try {
            res = functionModuleMapper.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.FUNCTION_MODULE_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.FUNCTION_MODULE_EDIT_ERROR.getCode() + " msg" + ErrorCode.FUNCTION_MODULE_EDIT_ERROR.getMsg());
            return result;
        }

        if(domain.getServiceIds() != null) {
            result = deleteModuleServcie(domain.getId());
            if(!result.isSuccess()) {
                return result;
            }
            result = addModuleService(domain.getId(), domain.getServiceIds());
        }

        return result;
    }



    @Override
    public ResultDO get(String id) {

        ResultDO result = new ResultDO();
        FunctionModuleEntity entity = null;

        try {
            entity = functionModuleMapper.selectById(id);
        } catch(Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }


        result = getModuleService(id);
        if(!result.isSuccess()) {
            return result;
        }

        FunctionModuleDO domain = getDomain(entity);

        domain.setServiceManagers((List<ServiceManagerDO>) result.getModel(ResultDO.FIRST_MODEL_KEY));
        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    @Override
    public ResultDO remove(String id, String modifier) {

        ResultDO result = isUse(id);

        if(!result.isSuccess()) {
            return result;
        }

        FunctionModuleEntity entity = new FunctionModuleEntity();

        entity.setId(id);
        entity.setIsDelete(Constant.IS_DELETE);
        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        int res = -1;
        try {
            res = functionModuleMapper.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.FUNCTION_MODULE_DELETE_ERROR);
            logger.debug("error code：" + ErrorCode.FUNCTION_MODULE_DELETE_ERROR.getCode() + " msg" + ErrorCode.FUNCTION_MODULE_DELETE_ERROR.getMsg());
            return result;
        }

        result = deleteModuleServcie(id);
        return result;
    }

    public ResultDO updateStatus(String id, int status, String modifier) {

        ResultDO result = new ResultDO();

        FunctionModuleEntity entity = new FunctionModuleEntity();

        entity.setId(id);
        entity.setStatus(status);
        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);

        int res = -1;
        try {
            res = functionModuleMapper.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(res < 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.FUNCTION_MODULE_SERVICE_DELETE_ERROR);
            logger.debug("error code：" + ErrorCode.FUNCTION_MODULE_SERVICE_DELETE_ERROR.getCode() + " msg" + ErrorCode.FUNCTION_MODULE_SERVICE_DELETE_ERROR.getMsg());
            return result;
        }

        return result;
    }

    public ResultDO getAvailableModule() {
        ResultDO result = new ResultDO();
        List<FunctionModuleEntity> list;
        try {
            list = functionModuleMapper.selectList(Wrappers.<FunctionModuleEntity>lambdaQuery()
                    .eq(FunctionModuleEntity::getStatus, Constant.ON)
                    .eq(FunctionModuleEntity::getIsDelete, Constant.IS_DELETE_FALSE));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<FunctionModuleDO> doList = getDomainList(list);
        result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
        return result;
    }

    private ResultDO isUse(String id) {
        ResultDO result = new ResultDO();
        int count = 0;
        try {
            count = moduleServiceMapper.selectCount(Wrappers.<ModuleServiceEntity>lambdaQuery().eq(ModuleServiceEntity::getModuleId, id));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        if(count != 0) {
            result.setErrorCode(ErrorCode.FUNCTION_MODULE_CANNOT_DELETE);
            result.setSuccess(false);
        }
        return result;
    }

    @Override
    public ResultDO find(FunctionModuleQueryDO query) {

        ResultDO result = new ResultDO();

        QueryWrapper<FunctionModuleEntity> wrapper = new QueryWrapper<FunctionModuleEntity>();

        if(StringUtils.isNotEmpty(query.getCategoryId())) {
            wrapper.eq("category_id", query.getCategoryId());
        }
        if(StringUtils.isNotEmpty(query.getModuleName())) {
            wrapper.like("module_name", query.getModuleName());
        }
        wrapper.eq("is_delete", Constant.IS_DELETE_FALSE);
        Page<FunctionModuleEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        IPage<FunctionModuleEntity> iPage = null;
        try {
            iPage = functionModuleMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<FunctionModuleDO> doList = getDomainList(iPage.getRecords());

        PageDO<FunctionModuleDO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    private FunctionModuleDO getDomain(FunctionModuleEntity entity) {
        ResultDO result = new ResultDO();
        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        FunctionModuleDO domain = new FunctionModuleDO();

        if(!result.isSuccess()) {
            return null;
        }
        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }


    private  List<FunctionModuleDO> getDomainList(List<FunctionModuleEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<FunctionModuleDO> doList = new ArrayList<>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(FunctionModuleEntity entity : list) {

                FunctionModuleDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }

}
